<template>
  <div class="divBox">
    <el-card class="box-card">
      <el-form inline size="small" @submit.native.prevent>
        <el-form-item label="房屋类型:">
          <el-select v-model="listPram.houseType" placeholder="全部" clearable style="width: 150px">
            <el-option
                v-for="item in houseTypeOptions"
                :key="item.value"
                :label="item.houseTypeName"
                :value="item.houseTypeName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房屋状态:">
          <el-select v-model="listPram.houseStatus" placeholder="全部" clearable style="width: 150px">
            <el-option
                v-for="item in houseStatusOptions"
                :key="item.value"
                :label="item.content"
                :value="item.content">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房屋:">
          <el-input v-model="listPram.houseKeyword" placeholder="租赁证编号、地址关键词" clearable style="width: 250px"/>
        </el-form-item>
        <el-form-item label="承租人:">
          <el-input v-model="listPram.lesseeKeyword" placeholder="姓名、身份证号、手机号关键词" clearable style="width: 250px"/>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="mini" type="primary" @click.native="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item class="el-form-item-align-right">
          <el-button
              icon="el-icon-upload2"
              @click="handleExport('multi')"
              type="primary" size="mini" v-has-permi="['admin:house:information:export']">
            批量导出
          </el-button>
        </el-form-item>
        <el-form-item class="el-form-item-align-right">
          <el-button icon="el-icon-upload2" size="mini" type="primary" v-has-permi="['admin:house:information:import']">批量导入
          </el-button>
        </el-form-item>
        <el-form-item class="el-form-item-align-right">
          <router-link :to=" { path:'/house/information/edit' } ">
            <el-button icon="el-icon-circle-plus-outline" size="mini" type="primary"
                       v-has-permi="['admin:house:information:save']">新增
            </el-button>
          </router-link>
        </el-form-item>
      </el-form>
      <el-table :data="listData.records" size="small" v-loading="tableLoading"
                :header-cell-style=" {fontWeight:'bold',background:'#f8f8f9',color: '#515a6e',height:'40px'}" border
                @selection-change="handleSelectionChange">
        <el-table-column type="expand" align="center" width="40">
          <template slot-scope="props">
            <el-row class="house-info-row">
              <span class="info-item">
                <span class="info-label">方位：</span>
                <span class="info-value">{{ props.row.houseDirection ||'-'}}</span>
              </span>
              <span class="info-item">
                  <span class="info-label">结构：</span>
                  <span class="info-value">{{ props.row.structureType  ||'-'}}</span>
              </span>
              <span class="info-item">
                  <span class="info-label">阳台建筑面积/使用面积：</span>
                  <span class="info-value">
                    {{ props.row.balconyBuildingArea === 0 && props.row.balconyUsableArea === 0 ? '-' : `${props.row.balconyBuildingArea}/${props.row.balconyUsableArea}` }}</span>
              </span>
              <span class="info-item">
                  <span class="info-label">阴台建筑面积/使用面积：</span>
                  <span class="info-value">
                     {{ props.row.shadyBalconyBuildingArea === 0 && props.row.shadyBalconyUsableArea === 0 ? '-' : `${props.row.shadyBalconyBuildingArea}/${props.row.shadyBalconyUsableArea}` }}
                  </span>
              </span>
              <span class="info-item">
                  <span class="info-label">地下室建筑面积/使用面积：</span>
                  <span class="info-value">
                    {{ props.row.basementBuildingArea === 0 && props.row.basementUsableArea === 0 ? '-' : `${props.row.basementBuildingArea}/${props.row.basementUsableArea}` }}
                  </span>
              </span>
              <span class="info-item">
                  <span class="info-label">其他建筑面积/使用面积：</span>
                  <span class="info-value">
                     {{ props.row.otherBuildingArea === 0 && props.row.otherUsableArea === 0 ? '-' : `${props.row.otherBuildingArea}/${props.row.otherUsableArea}` }}
                  </span>
              </span>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column align="center"
            type="selection"
            width="50">
        </el-table-column>
        <el-table-column align="center" label="ID" prop="id" width="60"></el-table-column>
        <el-table-column align="center" label="类型" width="60">
          <template slot-scope="scope">
            <span :class="`house-type-${scope.row.houseType}`">
              {{ scope.row.houseType }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="租赁证编号" prop="leaseCertificateNumberNew" width="70"/>
        <el-table-column label="地址" header-align="center">
          <el-table-column align="center" label="片区" prop="areaName" width="50"/>
          <el-table-column align="center" label="街（巷、路）" prop="streetName" min-width="80"/>
          <el-table-column align="center" label="号（楼、院）" prop="buildingNumber" width="60"/>
          <el-table-column align="center" label="单元" prop="unitNumber" width="40"/>
          <el-table-column align="center" label="楼层" prop="floorLevel" width="40"/>
          <el-table-column align="center" label="房号" prop="roomNumber" width="40"/>
        </el-table-column>
        <el-table-column align="center" label="门牌号" prop="buildingArea" width="70">
          <template slot-scope="scope">
            <span>{{ scope.row.buildingNumber}}-{{ scope.row.unitNumber}}-{{ scope.row.roomNumber}}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="建筑/使用面积（㎡）" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.buildingArea}}/{{ scope.row.usableArea}}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="初始租金标准" prop="unitPricePerSquare" width="110">
          <template slot-scope="scope">
            <span v-if="scope.row.houseType==='公租房'">{{ scope.row.unitPricePerSquare}}元/㎡(建筑面积)</span>
            <span v-else>{{ scope.row.unitPricePerSquare}}元/㎡(使用面积)</span>
          </template>
        </el-table-column>
        <el-table-column label="调节因素" header-align="center">
          <el-table-column align="center" label="地段" prop="pqxs" width="40"/>
          <el-table-column align="center" label="楼层" prop="lcxs" width="40"/>
          <el-table-column align="center" label="合计" prop="hjxs" width="40"/>
        </el-table-column>
        <el-table-column align="center" label="月租金" width="70">
          <template slot-scope="scope" >
              <span @click="showFormula(scope.row)" class="clickable-link">
                ￥{{ scope.row.totalPrice || 0}}
              </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="当前承租人"  width="95">
          <template slot-scope="scope">
            <span @click="handleLessee(scope.row.currentTenantIdCard)" class="clickable-link">
              {{ scope.row.currentTenantName }}_{{ scope.row.currentTenantIdCardLastFour }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="建立租赁时间" prop="leaseRelationshipTime" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.leaseRelationshipTime ||'-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="保证金状态" width="60">
          <template slot-scope="scope">
            <span
                @click="showDetail(scope.row)"
                :style="getStatusColor(scope.row)"
                style="cursor: pointer;">
              {{ getStatusText(scope.row) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="状态" width="50">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.houseStatus === '已租' ? 'green' : 'red' }">
              {{ scope.row.houseStatus ||'-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <router-link :to=" { path:'/house/information/edit/' + scope.row.id }">
              <el-button icon="el-icon-edit" size="mini" type="primary" style="margin-left: 10px"
                         v-has-permi="['admin:house:information:save']">编辑
              </el-button>
            </router-link>

            <router-link :to=" { path:'/house/information/edit/' + scope.row.id + '/1' }">
              <el-button icon="el-icon-s-unfold" size="mini" type="primary" style="margin-left: 10px"
                         v-has-permi="['admin:house:information:save']">详情
              </el-button>
            </router-link>

            <el-button icon="el-icon-delete" size="mini" type="danger" @click="handlerDelete(scope.row.id)" style="margin-left: 10px"
                       v-has-permi="['admin:house:information:delete']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          :current-page="listPram.page"
          :page-sizes="[10,20,40,60,80,100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="listData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>


    <el-dialog
        :visible.sync="dialogVisible"
        title="保证金详情"
        width="25%"
        class="custom-dialog"
        :modal-append-to-body="true"
        :close-on-click-modal="false"
    >
      <div v-if="currentRow" class="dialog-content">
        <div class="row">
          <p class="half-width"><strong>缴纳金额：</strong>{{ currentRow.newDeposit ||0 }}元</p>
          <p class="half-width"><strong>缴纳时间：</strong>{{ currentRow.newDepositPaymentTime ||'暂无' }}</p>
        </div>
        <div class="row">
          <p class="half-width"><strong>归还金额：</strong>{{ currentRow.newDepositReturned ||0 }}元</p>
          <p class="half-width"><strong>归还时间：</strong>{{ currentRow.newDepositReturnTime ||'暂无' }}</p>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="月租金计算公式" :visible.sync="dialogVisible2" width="50%">
      <div>
        <p><strong>计算公式：</strong>应交月租金 = 使用面积 x 调差后收费标准</p>
        <div v-if="currentRow2">
          <p style="margin-top: 10px;margin-left: 145px"  > =
            {{currentRow2.usableArea || 0}} x {{currentRow2.calculatedPrice || 0}} = ￥{{currentRow2.totalPrice || 0}}
          </p>
        </div>
      </div>
    </el-dialog>


  </div>
</template>

<script>

import {deleteRow, getAdminGetFwlx, getFwState, list} from "@/api/house";
import {checkPermi} from "@/utils/permission";
import {exportMultiColumn} from "@/api/export";

export default {
  components: {},
  data() {
    return {
      listData: {
        records: [], total: 0
      },
      listPram: {
        page: 1,
        limit: 10,
        houseKeyword: '',
        houseStatus: '',
        houseType: '',
        lesseeKeyword: '',
        uniqueId: '',
      },
      editDialog: {
        visible: false,
        isCreate: 0, // 0=创建，1=编辑
        editDate: {},
      },
      tableLoading: false,
      houseTypeOptions: [],
      houseStatusOptions: [],
      multipleSelection: [],
      dialogVisible: false,
      currentRow: null,
      dialogVisible2: false,
      currentRow2: null,
    }
  },
  mounted() {
    this.imageUrl = process.env.VUE_APP_IMAGE_URL

    // todo 获取查询参数(当前房屋)
    const currentHouse = this.$route.query.currentHouse; // 获取查询参数
    if (currentHouse) {
      this.listPram.uniqueId = currentHouse
      list(this.listPram).then(res => {
        this.listData = res;
      }).finally(() => {
      })
    }else {
      this.getList()
    }
    this.getHouseType()
    this.getHouseStatus()

  },
  methods: {
    checkPermi,
    getList() {
      this.tableLoading = true;
      list(this.listPram).then(res => {
        this.listData = res;
      }).finally(() => {
        this.tableLoading = false;
      });
    },
    handleSearch() {
      this.listPram.page = 1;
      this.getList();
    },
    getHouseType() {
      // 获取房屋类型
      getAdminGetFwlx().then((res) => {
        this.houseTypeOptions = res
      })
    },
    // 获取房屋状态
    getHouseStatus() {
      getFwState({dicType:'fwzt'}).then((res) => {
        this.houseStatusOptions = res
      })
    },
    openEdit(isCreate, editDate) {
      this.editDialog.editDate = editDate;
      this.editDialog.isCreate = isCreate;
      this.editDialog.visible = true
    },
    handlerDelete(id) {
      this.$confirm('确认删除该数据吗？').then(() => {
        const loading = this.$loading({text: '删除中', background: 'rgba(255,255,255,.5)'})
        deleteRow(id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        }).finally(() => {
          loading.close()
        })
      })
    },
    handleExport(){
      exportMultiColumn().then(() => {
      }).finally(() => {
      })
    },
    hideEditDialog() {
      this.editDialog.visible = false
      this.getList()
    },
    handleSizeChange(val) {
      this.listPram.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listPram.page = val
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    resetQuery() {
      this.listPram.houseKeyword = '';
      this.listPram.houseStatus = '';
      this.listPram.houseType = '';
      this.listPram.lesseeKeyword = '';
      this.listPram.page = 1;
      this.getList();
    },
    handleLessee(name) {
      this.$router.push({
        path: '/lessee/index',
        query: {
          currentTenantIdCard: name // 携带当前承租人名称作为查询参数
        }
      });
    },
    // 显示弹窗
    showDetail(row) {
      this.currentRow = row;
      this.dialogVisible = true;
    },
    // 显示弹窗
    showFormula (row) {
      this.currentRow2 = row;
      this.dialogVisible2 = true;
    },
    // 动态设置状态颜色
    getStatusColor(row) {
      if (row.newDeposit && row.newDepositPaymentTime && !row.newDepositReturned) {
        return { color: 'green' };
      } else if (row.newDepositReturned && row.newDepositReturnTime) {
        return { color: 'blue' };
      } else if (!row.newDeposit && !row.newDepositPaymentTime) {
        return { color: 'red' };
      }
      return { color: 'gray' }; // 默认异常状态
    },
    // 动态设置状态文本
    getStatusText(row) {
      if (row.newDeposit && row.newDepositPaymentTime && !row.newDepositReturned) {
        return "已缴纳";
      } else if (row.newDepositReturned && row.newDepositReturnTime) {
        return "已归还";
      } else if (!row.newDeposit && !row.newDepositPaymentTime) {
        return "未缴纳";
      }
      return "状态异常";
    }


  }
}
</script>

<style scoped lang="scss">
::v-deep .el-checkbox__inner {
  border-color: #1879fe;
}
.clickable-link {
  color: #1890ff;
  cursor: pointer;
  text-decoration: none;
}

.clickable-link:hover {
  text-decoration: underline;
  color: #1890ff;
}

.house-type-廉租房 { color: #42a2fc; }
.house-type-直管公房 { color: #70c919; }
.house-type-公租房 { color: #ffc159; }


.dialog-content {
  padding: 10px;
}
.dialog-content .row {
  display: flex;
  width: 100%;
  margin-bottom: 10px; /* Adjust as needed */
}

.dialog-content .half-width {
  width: 50%;
  margin: 0;
  padding: 0 5px; /* Add some spacing between columns */
  box-sizing: border-box;
}

.custom-dialog .el-dialog__body {
  padding: 10px 20px;
}

.dialog-content p {
  margin-bottom: 10px;
  line-height: 1.5;
}
.house-info-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px; /* 调整项与项之间的间距 */
  margin: 8px 0;
  font-size: 14px;
}

.info-item {
  display: inline-flex;
  align-items: center;
  margin-left: 50px;
}

.info-label {
  color: #909399; /* ElementUI的次要文字颜色 */
  margin-right: 4px;
}

.info-value {
  color: #606266; /* ElementUI的主要文字颜色 */
}
</style>
